package com.controller;

import com.api.CommonResult;
import com.api.Commons;
import com.entity.*;
import com.entity.table.FAddressTableDef;
import com.entity.table.FCartGoodsTableDef;
import com.mybatisflex.core.paginate.Page;
import com.service.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;
import java.util.UUID;

/**
 * 订单表 控制层。
 *
 * @author admin
 * @since 2024-05-30
 */
@Controller
@RequestMapping("/fOrder")
public class FOrderController {

    @Autowired
    private FOrderService fOrderService;
    @Autowired
    private FAddressService fAddressService;
    @Autowired
    private FCartService fCartService;
    @Autowired
    private FCartGoodsService fCartGoodsService;
    @Autowired
    private FOrderdetailService fOrderdetailService;

    /**
     * 添加订单表。
     *
     * @param fOrder 订单表
     * @return {@code true} 添加成功，{@code false} 添加失败
//     */
//    @PostMapping("save")
//    public boolean save(@RequestBody FOrder fOrder) {
//        return fOrderService.save(fOrder);
//    }

    /**
     * 根据主键删除订单表。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return fOrderService.removeById(id);
    }

    /**
     * 根据主键更新订单表。
     *
     * @param fOrder 订单表
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody FOrder fOrder) {
        return fOrderService.updateById(fOrder);
    }

    /**
     * 查询所有订单表。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<FOrder> list() {
        return fOrderService.list();
    }

    /**
     * 根据订单表主键获取详细信息。
     *
     * @param id 订单表主键
     * @return 订单表详情
     */
    @GetMapping("getInfo/{id}")
    public FOrder getInfo(@PathVariable Serializable id) {
        return fOrderService.getById(id);
    }

    /**
     * 分页查询订单表。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<FOrder> page(Page<FOrder> page) {
        return fOrderService.page(page);
    }

    /**
     * 提交订单，添加订单表
     *
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PostMapping("save")
    @ResponseBody
    @Transactional //使用数据库事务管理，若程序员执行过程中出错，回滚所有数据
    public CommonResult save(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            FUser user = (FUser) session.getAttribute("user");
            //读取收获地址
            FAddress fAddress = fAddressService.queryChain().where(FAddressTableDef.F_ADDRESS.USER_ID.eq(user.getId())).one();
            //如果用户没有设置收获地址，则跳转到收获地址设置页面
            if (fAddress == null) {
                return CommonResult.failed("/user_center_site");
            }
            //生成唯一订单号
            String order_no = UUID.randomUUID().toString().replace("-","").substring(12);
            //读取购物车
            FCart fCart = fCartService.getUserCartInfo(user.getId());
            FOrder fOrder = FOrder.builder().orderNo(order_no)//订单编号
                    .address(fAddress.getAddress())//收货地址
                    .phone(fAddress.getPhone())//联系方式
                    .time(Commons.nowDate())//下单时间
                    .userId(user.getId())//用户id
                    .userName(fAddress.getUserName())//收货时间
                    .totalPrice(fCart.getTotalPrice())//订单总价
                    .build();
            //数据插入订单表
            fOrderService.save(fOrder);
            for (BGoods bGoods : fCart.getGoods()) {
                //添加订单详情记录
                FOrderdetail fOrderDetail = FOrderdetail.builder().orderId(fOrder.getId())//订单id
                        .goodName(bGoods.getGoodName())//商品名称
                        .imgUrl(bGoods.getImgUrl())//商品图片
                        .intro(bGoods.getIntro())//商品介绍
                        .unit(bGoods.getUnit())//商品单位
                        .num(bGoods.getNum())//商品数量
                        .price(bGoods.getPrice())//商品价格
                        .totalPrice(bGoods.getTotalPrice())//商品总价
                        .build();
                //统计单个商品总价
                fOrderDetail.setTotalPrice(bGoods.getTotalPrice());
                fOrderdetailService.save(fOrderDetail);
            }
            //添加订单成功，清空购物车
            fCartService.removeById(fCart.getId());
            fCartGoodsService.remove(FCartGoodsTableDef.F_CART_GOODS.CART_ID.eq(fCart.getId()));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//数据库出错，回滚所有操作
            e.printStackTrace();
            return CommonResult.failed("/login");
        }
        return CommonResult.success("成功提交订单");
    }
}
